<template>
  <div class="page-container">
    <Header/>

    <div class="main-content">
      <!-- 搜索结果区域 -->
      <div class="search-container">
        <!-- 固定头部区域 -->
        <div class="fixed-header">
          <!-- 搜索栏 -->
          <div class="search-bar-wrapper">
            <SearchBar :is-in-search-page="true" @search="handleSearch"/>
          </div>

          <!-- 搜索信息 -->
          <div class="search-info">
            <h2 class="search-title">
              搜索结果：<span class="keyword">"{{ searchQuery }}"</span>
            </h2>
            <p v-if="totalResults" class="result-count">
              共找到 {{ totalResults }} 个相关结果
            </p>
          </div>

          <!-- 分类筛选 -->
          <div class="filter-bar">
            <div class="filter-options">
              <span
                  v-for="tag in categoryTags"
                  :key="tag.id"
                  :class="['filter-option', { active: tagId === tag.id }]"
                  @click="filterByTag(tag.id)"
              >
                {{ tag.name }}
              </span>
            </div>
          </div>
        </div>

        <!-- 内容展示区域 -->
        <div class="content-wrapper">
          <!-- 加载状态 -->
          <div v-if="loading" class="content-box loading">
            <div class="loading-spinner"></div>
            <p>搜索中...</p>
          </div>

          <!-- 有结果状态 -->
          <div v-else-if="results.length" class="content-box">
            <div class="results-grid">
              <content-card
                  v-for="(item, index) in results"
                  :key="index"
                  :item="item"
                  @click="handleItemClick(item)"
                  @imageLoad="handleImageLoad(index)"
              />
            </div>
          </div>

          <!-- 空状态 -->
          <div v-else class="content-box">
            <div class="empty-state">
              <div class="empty-content">
                <div class="empty-icon-wrapper">
                  <i class="el-icon-search"></i>
                  <div class="empty-dots">
                    <span></span>
                    <span></span>
                    <span></span>
                  </div>
                </div>
                <h3 class="empty-title">暂无搜索结果</h3>
                <p class="empty-desc">
                  抱歉，没有找到与"<span class="highlight">{{ searchQuery }}</span>"相关的内容
                </p>
                <div class="empty-tips">
                  <div class="tips-title">建议您：</div>
                  <ul>
                    <li>
                      <i class="el-icon-check"></i>
                      <span>检查输入是否正确</span>
                    </li>
                    <li>
                      <i class="el-icon-check"></i>
                      <span>尝试其他关键词</span>
                    </li>
                    <li>
                      <i class="el-icon-check"></i>
                      <span>切换其他分类搜索</span>
                    </li>
                  </ul>
                </div>
                <div class="empty-actions">
                  <button class="back-btn primary" @click="$router.push('/')">
                    <i class="el-icon-back"></i>
                    返回首页
                  </button>
                  <button class="back-btn secondary" @click="clearSearch">
                    <i class="el-icon-refresh"></i>
                    重新搜索
                  </button>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <SideMenu/>
    <Footer/>
  </div>
</template>

<script>
import Header from '@/components/layout/Header.vue'
import Footer from '@/components/layout/Footer.vue'
import ContentCard from '@/components/common/ContentCard.vue'
import SearchBar from '@/components/SearchBar.vue'
import SideMenu from "@/components/SideMenu.vue";
import {getTagList, inquireArticle} from "@/api/portalAPI";

export default {
  name: 'SearchResults',
  components: {
    SideMenu,
    Header,
    Footer,
    ContentCard,
    SearchBar
  },
  data() {
    return {
      loading: true,
      results: [],
      originalResults: [],
      totalResults: 0,
      categoryTags: [{ id: null, name: '全部' }],
      tagId: null
    }
  },
  computed: {
    searchQuery() {
      return this.$route.query.q || null
    },
    categoryId() {
      return this.$route.query.type === 'all' ? null : (this.$route.query.type || null)
    }
  },
  watch: {
    '$route.query': {
      handler() {
        this.resetSearch()
        this.fetchResults()
      },
      immediate: true
    }
  },
  mounted() {
    this.getTagLists()
  },
  methods: {
    async getTagLists() {
      try {
        const { code, data, msg } = await getTagList()
        if (code === 0) {
          this.categoryTags = [...this.categoryTags, ...data]
        } else {
          console.error('Error fetching tags:', msg)
        }
      } catch (error) {
        console.error('API call failed:', error)
      }
    },

    async fetchResults() {
      this.loading = true
      try {
        const { code, data, msg } = await inquireArticle({
          keywords: this.searchQuery,
          categoryId: this.categoryId,
          tagId: this.tagId
        })
        
        if (code === 0) {
          const processedData = data.map(item => ({
            ...item,
            loaded: false
          }))
          this.results = processedData
          this.originalResults = processedData
          this.totalResults = this.results.length
        } else {
          console.error('Error fetching articles:', msg)
        }
      } catch (error) {
        console.error('搜索失败:', error)
      } finally {
        this.loading = false
      }
    },

    resetSearch() {
      this.results = []
      this.originalResults = []
      this.loading = true
      this.tagId = null
    },

    filterByTag(id) {
      this.tagId = id
      
      if (id === null) {
        this.fetchResults()
      } else {
        this.results = this.originalResults.filter(item => 
          item.tagIds.includes(id)
        )
        this.totalResults = this.results.length
      }
    },

    handleImageLoad(index) {
      setTimeout(() => {
        this.$set(this.results[index], 'loaded', true)
      }, 100)
    },

    handleItemClick(item) {
      this.$router.push({
        name: 'Detail',
        params: { id: item.id }
      })
    },

    handleSearch({ q, type }) {
      if (this.$route.query.q === q && this.$route.query.type === type) {
        this.resetSearch()
        this.fetchResults()
        return
      }

      this.$router.push({
        query: { q, type }
      }).catch(err => {
        if (err.name !== 'NavigationDuplicated') {
          throw err
        }
        this.resetSearch()
        this.fetchResults()
      })
    },

    clearSearch() {
      this.tagId = null
      this.$router.push({
        query: {}
      })
    }
  }
}
</script>

<style scoped>
/* 页面基础布局 */
.page-container {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
}

.main-content {
  background: var(--bg-color);
  padding: 20px 0 40px;
  min-height: calc(100vh - 60px);
  width: 100%;
}

/* 搜索容器 */
.search-container {
  max-width: var(--container-width);
  margin: 0 auto;
  width: 100%;
  padding: 0 20px; /* 在最外层容器统一控制左右间距 */
}

/* 固定头部 */
.fixed-header {
  margin-bottom: 20px;
  width: 100%;
}

/* 搜索栏 */
.search-bar-wrapper {
  margin-bottom: 20px;
  background: var(--card-bg);
  border-radius: 8px;
  padding: 16px 20px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
}

/* 搜索信息 */
.search-info {
  margin-bottom: 20px;
  text-align: center;
}

.search-title {
  font-size: 18px;
  font-weight: 500;
  color: var(--text-color);
  margin-bottom: 10px;
  text-align: center;
}

.keyword {
  color: var(--primary-color);
  font-weight: 600;
}

.result-count {
  font-size: 14px;
  color: var(--secondary-color);
  text-align: center;
}

/* 筛选栏 */
.filter-bar {
  background: var(--card-bg);
  padding: 16px 20px; /* 恢复左右内边距 */
  border-radius: 8px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.filter-label {
  font-size: 14px;
  color: var(--secondary-color);
  margin-right: 16px;
  white-space: nowrap;
}

.filter-options {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  flex: 1;
}

.filter-option {
  padding: 6px 16px;
  border-radius: 16px;
  font-size: 13px;
  cursor: pointer;
  background: var(--hover-color);
  color: var(--text-color);
  transition: all 0.3s;
}

.filter-option:hover,
.filter-option.active {
  background: var(--primary-color);
  color: white;
}

/* 内容区域 */
.content-wrapper {
  background: var(--card-bg);
  border-radius: 8px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
  width: 100%;
}

.content-box {
  min-height: 400px;
  padding: 0px; /* 与筛选栏保持一致的内边距 */
  width: 100%;
}

/* 结果网格 */
.results-grid {
  display: grid;
  grid-template-columns: repeat(5, 1fr);
  gap: 20px; /* 调整间距使其与内边距匹配 */
  width: 100%;
}

/* 加载状态 */
.content-box.loading {
  position: relative;
}

.loading-spinner {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 40px;
  height: 40px;
  border: 3px solid var(--hover-color);
  border-top-color: var(--primary-color);
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

.content-box.loading p {
  position: absolute;
  top: calc(50% + 30px);
  left: 50%;
  transform: translateX(-50%);
  color: var(--secondary-color);
}

@keyframes spin {
  to {
    transform: translate(-50%, -50%) rotate(360deg);
  }
}

/* 空状态 */
.empty-state {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 500px;
  padding: 40px 20px;
  background: var(--card-bg);
  border-radius: 12px;
}

.empty-content {
  text-align: center;
  max-width: 440px;
}

.empty-icon-wrapper {
  position: relative;
  display: inline-block;
  margin-bottom: 24px;
}

.empty-icon-wrapper i {
  font-size: 80px;
  color: var(--primary-color);
  opacity: 0.8;
}

.empty-dots {
  position: absolute;
  bottom: -5px;
  right: -15px;
  display: flex;
  gap: 4px;
}

.empty-dots span {
  width: 8px;
  height: 8px;
  background: var(--primary-color);
  border-radius: 50%;
  opacity: 0.6;
  animation: dotFade 1.4s infinite;
}

.empty-dots span:nth-child(2) {
  animation-delay: 0.2s;
}

.empty-dots span:nth-child(3) {
  animation-delay: 0.4s;
}

@keyframes dotFade {
  0%, 100% {
    opacity: 0.2;
  }
  50% {
    opacity: 0.7;
  }
}

.empty-title {
  font-size: 28px;
  color: var(--text-color);
  margin-bottom: 12px;
  font-weight: 600;
}

.empty-desc {
  color: var(--secondary-color);
  font-size: 16px;
  line-height: 1.6;
  margin-bottom: 32px;
}

.highlight {
  color: var(--primary-color);
  font-weight: 500;
}

.empty-tips {
  background: var(--bg-color);
  padding: 24px;
  border-radius: 12px;
  text-align: left;
  margin-bottom: 32px;
}

.tips-title {
  color: var(--text-color);
  font-size: 16px;
  font-weight: 500;
  margin-bottom: 16px;
}

.empty-tips ul {
  list-style: none;
}

.empty-tips li {
  display: flex;
  align-items: center;
  gap: 8px;
  color: var(--secondary-color);
  font-size: 15px;
  margin-bottom: 12px;
}

.empty-tips li:last-child {
  margin-bottom: 0;
}

.empty-tips li i {
  color: var(--primary-color);
  font-size: 16px;
}

.empty-actions {
  display: flex;
  justify-content: center;
  gap: 16px;
}

.back-btn {
  display: inline-flex;
  align-items: center;
  gap: 8px;
  padding: 12px 24px;
  border-radius: 25px;
  font-size: 15px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
  border: none;
}

.back-btn.primary {
  background: var(--primary-color);
  color: white;
  box-shadow: 0 4px 12px rgba(var(--primary-color-rgb), 0.2);
}

.back-btn.secondary {
  background: var(--hover-color);
  color: var(--text-color);
}

.back-btn:hover {
  transform: translateY(-2px);
}

.back-btn.primary:hover {
  box-shadow: 0 6px 16px rgba(var(--primary-color-rgb), 0.3);
  filter: brightness(1.1);
}

.back-btn.secondary:hover {
  background: var(--border-color);
}

/* 加载更多按钮 */
.load-more {
  padding: 40px 0;
  text-align: center;
  cursor: pointer;
  transition: all 0.3s;
}

.load-more-content {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  padding: 12px 28px;
  background: var(--card-bg);
  border: 1px solid var(--border-color);
  border-radius: 25px;
  color: var(--secondary-color);
  font-size: 14px;
  transition: all 0.3s;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.load-more:hover .load-more-content {
  color: var(--primary-color);
  border-color: var(--primary-color);
  background: linear-gradient(to right, var(--hover-color), var(--card-bg));
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
}

.load-more-text {
  margin-left: 8px;
  font-weight: 500;
}

.load-more-icon {
  transition: all 0.3s;
  width: 20px;
  height: 20px;
}

.circle-bg {
  opacity: 0.2;
}

.arrow {
  transform-origin: center;
  transition: transform 0.3s;
}

.load-more:hover .load-more-icon {
  animation: bounce 1s infinite;
}

@keyframes bounce {
  0%, 100% {
    transform: translateY(0);
  }
  50% {
    transform: translateY(3px);
  }
}

/* 响应式调整 */
@media (max-width: 1400px) {
  .results-grid {
    grid-template-columns: repeat(4, 1fr);
  }
}

@media (max-width: 1200px) {
  .results-grid {
    grid-template-columns: repeat(3, 1fr);
  }
}

@media (max-width: 768px) {
  .search-container {
    padding: 0 15px;
  }

  .filter-bar {
    padding: 12px 15px;
  }

  .content-box {
    padding: 15px;
  }

  .results-grid {
    grid-template-columns: repeat(2, 1fr);
    gap: 15px;
  }

  .load-more {
    padding: 30px 0;
  }

  .load-more-content {
    padding: 10px 24px;
    font-size: 13px;
  }

  .search-bar-wrapper {
    padding: 12px 15px;
    margin-bottom: 15px;
  }

  .empty-state {
    min-height: 400px;
    padding: 30px 15px;
  }

  .empty-icon-wrapper i {
    font-size: 64px;
  }

  .empty-title {
    font-size: 24px;
  }

  .empty-desc {
    font-size: 15px;
    margin-bottom: 24px;
  }

  .empty-tips {
    padding: 20px;
  }

  .tips-title {
    font-size: 15px;
    margin-bottom: 12px;
  }

  .empty-tips li {
    font-size: 14px;
    margin-bottom: 10px;
  }

  .back-btn {
    padding: 10px 20px;
    font-size: 14px;
  }
}

@media (max-width: 480px) {
  .search-container {
    padding: 0 12px;
  }

  .filter-bar {
    padding: 10px 12px;
  }

  .content-box {
    padding: 0px;
  }

  .results-grid {
    gap: 12px;
  }

  .load-more {
    padding: 20px 0;
  }

  .load-more-content {
    padding: 8px 20px;
    font-size: 12px;
  }

  .search-bar-wrapper {
    padding: 10px 12px;
    margin-bottom: 12px;
  }

  .empty-state {
    min-height: 350px;
    padding: 24px 12px;
  }

  .empty-icon-wrapper i {
    font-size: 56px;
  }

  .empty-title {
    font-size: 20px;
  }

  .empty-desc {
    font-size: 14px;
    margin-bottom: 20px;
  }

  .empty-tips {
    padding: 16px;
  }

  .tips-title {
    font-size: 14px;
  }

  .empty-tips li {
    font-size: 13px;
    margin-bottom: 8px;
  }

  .empty-actions {
    flex-direction: column;
    gap: 12px;
  }

  .back-btn {
    width: 100%;
    padding: 10px 16px;
    font-size: 13px;
    justify-content: center;
  }
}
</style>
